<?php

namespace App\Http\Controllers\supplier;

use App\Models\Admin\Supplier;
use App\Models\Admin\SupplierConfiguration;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use App\Http\Controllers\Controller;
use Illuminate\Support\Str;

class AuthController extends Controller
{
    /**
     * @param Request $request
     */
    public function __construct(public Request $request)
    {
        $this->middleware("auth:support", ['except' => ['login', 'refresh']]);
    }

    /**
     * @return JsonResponse
     */
    public function login(): JsonResponse
    {
        // TODO 验证码处理
        $credentials = $this->request->only(['phone', 'password']);
        $token = auth('support')->attempt($credentials);
        if (!$token) {
            return $this->sendError("登录失败");
        }
        return $this->respondWithToken($token, '登录成功');
    }

    /**
     * Log the user out (Invalidate the token).
     *
     * @return JsonResponse
     */
    public function logout(): JsonResponse
    {
        auth('support')->logout();

        return $this->sendResponse('bye bye', '退出成功');
    }

    /**
     * Refresh a token.
     *
     * @return JsonResponse
     */
    public function refresh(): JsonResponse
    {
        return $this->respondWithToken(auth('support')->refresh(), '刷新成功');
    }

    /**
     * @param string $token
     * @param string $message
     * @return JsonResponse
     */
    protected function respondWithToken(string $token, string $message): JsonResponse
    {
        /** @var Supplier $user **/
        $user = auth('support')->user();
        $host['domain'] = '';
        if ($message != '刷新成功'){
            $host = SupplierConfiguration::where('sid',$user['id'])->first();
            if ($user['account_verification'] == 1){
                if (empty($host['domain'])){
                    return $this->sendError("未绑定域名地址");
                }
                if ($host['domain_ssl'] ==1){
                    $host['domain'] = 'https://'.$host['domain'].'/sup';
                }else{
                    $host['domain'] = 'http://'.$host['domain'].'/sup';
                }
            }
            $user->id_number = substr($user->id_number,0,5).'*****************'.substr($user->id_number,14,4);
        }
        return $this->sendResponse([
            'host'=> $host['domain'],
            'user'=> $user,
            'access_token' => $token,
            'token_type' => 'Bearer',
            'expires_in' => auth('support')->factory()->getTTL() * 60
        ], $message);
    }
}
